<!--  -->
<template>
    <el-dialog class="adddialog" v-model="dialogVisible" title="添加费用" width="600" :before-close="handleClose">

        <div>

        
            <el-form  ref="ruleFormRef" :model="ruleForm" :rules="rules" class="ruleFormRef"  label-width="auto" status-icon>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="ruleForm.type" placeholder="请选择类型">
                        <el-option v-for="item in freeTypes" :label="item.name" :value="item.name" />
                        
                    </el-select>
                </el-form-item>
                <el-form-item label="金额" prop="price">
                    <el-input v-model="ruleForm.price" />
                </el-form-item>
                <el-form-item label="账期" prop="date">
                    <el-date-picker @change="dateChange" v-model="ruleForm.date" type="daterange"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD" unlink-panels range-separator="至"
                        start-placeholder="起始日期" end-placeholder="截止日期" />
                </el-form-item>
                <el-form-item label="小区" prop="buildingids">
                    <el-cascader @change="cascaderChange" :props="props" placeholder="请选择楼栋" clearable
                        v-model="ruleForm.buildingids" :options="buildings" />
                </el-form-item>
                <el-form-item prop="isAll"  label="房间">
                    <el-radio-group v-model="ruleForm.isAll">
                        <el-radio :value="1">全部房间</el-radio>
                        <el-radio @click.native="radioHandle" :value="0">部分房间</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="ruleForm.isAll==0">
                    <el-table :data="houses" style="width: 100%">
                        <el-table-column prop="building" label="楼栋" />
                        <el-table-column fixed prop="houseno" label="房间号" width="100" />
                        <el-table-column label="操作" width="80">
                            <template #default="scope">
                                <el-button @click="delHouse(scope.$index)" type="danger" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>


            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submit">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
    <House :buildingid="ruleForm.buildingid" @close="houseClose" v-if="houseDialogVisible"></House>
</template>

<script lang='ts' setup>
import { Free } from '../../service/fee/type';
import { getFeeTypeList,add } from '../../service/fee/fee';
import { getBuildingList } from '../../service/building/building'
import { reactive,  ref, onMounted, defineEmits } from 'vue'
import type {  FormInstance, FormRules } from 'element-plus'
// import { watch } from 'vue';
import House from './House.vue';
const dialogVisible = ref(true)
const houseDialogVisible = ref(false)
const emits = defineEmits(["close"])
const handleClose = () => {
    emits("close");
}
// const dateValue = ref([])

const dateChange = (e: any) => {
    console.log(e);
    if (e != null) {
        ruleForm.begindate = e[0];
        ruleForm.enddate = e[1]
    }
    else {
        ruleForm.begindate = "";
        ruleForm.enddate = ""
    }

}
const props = { label: "name", value: "id", checkStrictly: true }
const ruleForm = reactive<Free>({
    type: "",
    begindate: "",
    enddate: "",
    price: null,
    buildingid: 0,
    houseids: [],
    date: [],
    buildingids: [],
    isAll: 1
})
const ruleFormRef = ref<FormInstance>()
//表单校验

const validatorHouse=(rule: any, value: any, callback: any)=>{
    console.log(rule);
    
   
    if(value==0 && houses.value.length===0){
        callback(new Error("请选择房间"))
    }
    else{
        callback()
    }
    
}
 
var validatorPrice = (rule:any, value:any, callback:any) => {
    console.log(rule);
    var reg = /^\d+(?=\.{0,1}\d+$|$)/
    if(reg.test(value)) {
      callback()
    }else{
      callback(new Error('请输入大于等于0的正数'))
    }
  };


 
const rules = reactive<FormRules<Free>>({
    type: [
    { required: true, message: '请选择类型', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {validator:validatorPrice, trigger: 'blur'}
  ],
  date: [
    { required: true, message: '请选择账期', trigger: 'blur' }
  ],
  buildingids: [
    { required: true, message: '请选择楼栋', trigger: 'blur' }
  ],
  isAll:[{validator:validatorHouse, trigger: 'change'}]
})

const houses = ref<any[]>([]);

//删除选中的房间
const delHouse=(index:number)=>{

    // houses.value.splice(index,1);
    houses.value=houses.value.filter((_,ind)=>ind!=index);

}

//如果选择部分房间 弹出房间选择

const radioHandle = () => {
 
    houseDialogVisible.value = true;
}


//获取楼栋数据
const buildings = ref<any>([]);
const getBuildingData = async () => {

    const res: any = await getBuildingList(null);
    console.log(11111, res);
    if (res.errCode === 10000) {
        buildings.value = res.data.list;
    }

}

const cascaderChange = (e: any) => {

    console.log(e);
    if (!e) {
        ruleForm.buildingid = 0;
    }
    else {
        ruleForm.buildingid = e[e.length - 1];
    }

}

//接收 选中的房间

const houseClose = (data: any) => {

    houseDialogVisible.value = false;

    houses.value = data;


}
//获取费用类型
const freeTypes=ref<any[]>([]);
const getFreeTypeData=async ()=>{

    const res:any=await getFeeTypeList({psize:100});
    if(res.errCode===10000){
        freeTypes.value=res.data.list;
    }
}
onMounted(() => {
    getBuildingData();
    getFreeTypeData();
})


//提交表单

const addData=async ()=>{
    if(ruleForm.isAll){
        ruleForm.houseids=[];
    }  
    else if(houses.value.length>0){
        ruleForm.houseids= houses.value.map(item=>item.id)
    }
 

     const res:any= await add(ruleForm);
     console.log(res);
     if(res.errCode===10000){
        emits("close",true);
     }
     else{
        //提示提交失败
     }
}
const submit=async ()=>{
    //表单验证
   await  ruleFormRef.value?.validate((valid) => {
    if (valid) {
        addData();
    }
   }
)


}
</script>
<style scoped>
.ruleFormRef {
    padding: 10px 50px;
}
</style>